/**
 * 全站路由配置
 *
 * 建议:
 * 1. 代码中路由统一使用name属性跳转(不使用path属性)
 */
import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
Vue.use(Router)

// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
const _import = require('./import-' + process.env.NODE_ENV)

const router = new Router({
  routes: [
    { path: '/404', component: _import('common/404'), name: '404', meta: { title: '404未找到' } },
    { path: '/login', component: _import('common/login'), name: 'login', meta: { title: '登录' } },

    { path: '/',
      component: _import('main'),
      name: 'main',
      redirect: {name: 'home'},
      meta: { title: '主入口整体布局' },
      children: [
        { path: '/home', component: _import('common/home'), name: 'home', meta: { title: '首页', isTab: false } },
        // 系统设置路由模块
        { path: '/admin', component: _import('system/admin'), name: 'admin', meta: { title: '管理员列表', isTab: true } },
        { path: '/role', component: _import('system/role'), name: 'role', meta: { title: '角色列表', isTab: true } },
        { path: '/menu', component: _import('system/menu'), name: 'menu', meta: { title: '菜单列表', isTab: true } },
        { path: '/log', component: _import('system/log'), name: 'log', meta: { title: '日志列表', isTab: true } },
        { path: '/theme', component: _import('common/theme'), name: 'theme', meta: { title: '主题' } },
        { path: '/onLineUser', component: _import('monitor/onLineUser'), name: 'onLineUser', meta: { title: '在线用户管理', isTab: true } },
        { path: '/dict', component: _import('system/dict'), name: 'dict', meta: { title: '字典管理', isTab: false } },
        { path: '/dictValue', component: _import('system/dictValue'), name: 'dictValue', meta: { title: '字典值管理', isTab: false, target_new: false } },
      ]
    }
  ]
})

router.beforeEach(function (to, from, next) {
  let tokenInfo = store.getters['user/getTokenInfo']
  if (to.path === '/login') {
    if (tokenInfo && tokenInfo.access_token) {
      next({ name: 'home' })
    } else {
      next()
    }
  } else {
    if (!tokenInfo.access_token) {
      next({ name: 'login' }) // 没有token 跳转登录页面
    }
    next()
  }
})

export default router
